/* Copyright 2013-2015 www.snakerflow.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.snaker.engine.handlers.impl;

import org.snaker.engine.SnakerException;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.core.Execution;
import org.snaker.engine.entity.HistoryTask;
import org.snaker.engine.entity.Task;
import org.snaker.engine.model.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 包容网关合并分支操作的处理器
 *
 * @author yuqs
 * @since 1.0
 */
public class InclusiveMergeBranchHandler extends AbstractMergeHandler {
    private InclusiveJoinModel model;

    public InclusiveMergeBranchHandler(InclusiveJoinModel model) {
        this.model = model;
    }

    /**
     * 对join节点的所有输入变迁进行递归，查找join至fork节点的所有中间task元素
     *
     * @param execution
     * @see AbstractMergeHandler#findActiveNodes(Execution)
     */
    protected String[] findActiveNodes(Execution execution) {
        //  找到InclusiveForkModel
        List<TransitionModel> inputs = model.getInputs();
        InclusiveForkModel inclusiveForkModel = findInclusiveForkModel(inputs.get(0));
        if (inclusiveForkModel == null) {
            throw new SnakerException("可能是流程设计有误，未找到与之匹配的InclusiveForkModel。");
        }

        //  找到最初流向的分支
        List<TransitionModel> forkModelOutputs = inclusiveForkModel.getOutputs();
        Map<TransitionModel, String> tmOutputsMap = new HashMap<>();
        for (TransitionModel tm : forkModelOutputs) {
            NodeModel target = tm.getTarget();
            if (TaskModel.class.isInstance(target)) {
                tmOutputsMap.put(tm, target.getName());
            }
        }
        List<HistoryTask> historyTasks = execution.getEngine().query().getHistoryTasks(new QueryFilter().setOrderId(execution.getOrder().getId()).setNames(tmOutputsMap.values().toArray(new String[0])));
        List<Task> activeTasks = execution.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(execution.getOrder().getId()).setNames(tmOutputsMap.values().toArray(new String[0])));

        Set<String> existTaskNames = historyTasks.stream().map(HistoryTask::getTaskName).collect(Collectors.toSet());
        existTaskNames.addAll(activeTasks.stream().map(Task::getTaskName).collect(Collectors.toSet()));
        List<TransitionModel> foundOutputs = tmOutputsMap.entrySet().stream()
                .filter(e -> existTaskNames.contains(e.getValue()))
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        //  找到最初流向的分支 下的所有task name
        Set<String> foundTaskNames = new HashSet<>();
        Set<String> searchedTrans = new HashSet<>();
        findForkTaskNames(foundOutputs, searchedTrans, foundTaskNames);
        searchedTrans.clear();
        searchedTrans = null;

        String[] taskNames = foundTaskNames.toArray(new String[0]);
        return taskNames;
    }

    //  找到InclusiveForkModel
    private InclusiveForkModel findInclusiveForkModel(TransitionModel transitionModel) {
        NodeModel source = transitionModel.getSource();
        if (InclusiveForkModel.class.isInstance(source)) {
            return (InclusiveForkModel) source;
        }
        for (TransitionModel input : source.getInputs()) {
            return findInclusiveForkModel(input);
        }
        return null;
    }


    /**
     * 对join节点的所有输入变迁进行递归，查找join至fork节点的所有中间task元素
     *
     * @param outputs
     * @param foundTaskNames
     */
    private void findForkTaskNames(List<TransitionModel> outputs, Set<String> searchedTrans, Set<String> foundTaskNames) {
        for (TransitionModel tm : outputs) {
            if(searchedTrans.contains(tm.getName())){
                continue;
            }
            searchedTrans.add(tm.getName());
            NodeModel target = tm.getTarget();
            if(target.getName().equals(model.getName())){
                continue;
            }
            if (target instanceof WorkModel) {
                foundTaskNames.add(target.getName());
            }
            findForkTaskNames(target.getOutputs(), searchedTrans, foundTaskNames);
        }
    }
}
